package logic

import (
	"api/internal/svc"
	"api/internal/types"
	"api/pkg"
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"order_srv/order"
	"shop_srv/goods"
	"strconv"
)

type CreateOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderRequest) (resp *types.Response, err error) {

	//判断商品是否存在(根据商品详情)
	goodsId, err := l.svcCtx.GoodsSrv.GetGoodsByGoodsId(l.ctx, &goods.GetGoodsByGoodsIdRequest{GoodsId: req.GoodsId})
	//fmt.Println("创建订单,信息商品", goodsId)
	if err != nil {
		return &types.Response{Code: -1, Message: "服务器内部错误", Data: nil}, nil
	}
	if goodsId.GoodsId == 0 {
		return &types.Response{Code: -2, Message: "商品不存在", Data: nil}, nil
	}
	//商品数量是否充足(库存)
	stock, err := l.svcCtx.GoodsSrv.GetGoodsStock(l.ctx, &goods.GetGoodsStockRequest{GoodsId: req.GoodsId})
	if err != nil {
		return &types.Response{Code: -3, Message: "服务器内部错误", Data: nil}, nil
	}
	fmt.Println(stock.GoodsStatus, 1111)
	fmt.Println(req.Num, 2222)
	if stock.GoodsStatus < req.Num {
		return &types.Response{Code: -4, Message: "商品库存不足", Data: nil}, nil
	}
	//计算总金额
	amount := goodsId.GoodsPrice * req.Num
	fmt.Println(amount)
	logx.Debug("创建订单的商品总金额")
	//生成订单编号uuid
	orderSn := uuid.NewString()
	fmt.Println(orderSn)
	//创建订单
	userId := l.ctx.Value("userId").(string)
	uid, _ := strconv.Atoi(userId) //(uuid生成唯一标识)
	fmt.Println(uid)

	orders, err := l.svcCtx.OrderSrv.CreateOrder(l.ctx, &order.CreateOrderRequest{
		OrderSn: orderSn,
		Amount:  amount,
		UserId:  int64(uid),
		Payment: req.Payment,
	})
	if err != nil {
		return &types.Response{
			Code:    -5,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}
	//创建订单商品记录
	_, err = l.svcCtx.OrderSrv.CreateOrderItem(l.ctx, &order.CreateOrderItemRequest{
		OrderSn:    orderSn,
		OrderId:    orders.OrderId,
		GoodsId:    req.GoodsId,
		Quantity:   req.Num,
		GoodsPrice: goodsId.GoodsPrice,
		GoodsTitle: goodsId.GoodsTitle,
		GoodsCover: goodsId.GoodsCover,
	})
	//  扣减虚拟库存
	_, err = l.svcCtx.GoodsSrv.DeleteGoodsStock(l.ctx, &goods.DeleteGoodsStockRequest{
		GoodsId: req.GoodsId,
		Num:     req.Num,
	})
	if err != nil {
		return &types.Response{
			Code:    -6,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}
	//选择支付方式
	//totalAmount := amount / 100
	alipay := pkg.Alipay{
		Subject:     "商品支付",
		OutTradeNo:  orderSn,
		TotalAmount: "999",
	}
	url := alipay.Pay()
	return &types.Response{
		Code:    0,
		Message: "订单创建成功",
		Data: map[string]interface{}{
			"pay_url": url,
		},
	}, nil
}
